package com.itliang.mqtt.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itliang.constant.MqttConstants;
import com.itliang.core.model.entity.equipment.Equipment;
import com.itliang.core.redis.RedisCache;
import com.itliang.exception.BusinessException;
import com.itliang.mqtt.model.HardwareCode;
import com.itliang.mqtt.model.HardwareData;
import com.itliang.mqtt.service.MqttService;
import com.itliang.mqtt.service.SubscribeDataService;
import com.itliang.service.hardware.EquipmentDataService;
import com.itliang.service.hardware.EquipmentService;
import com.itliang.utils.mqtt.MqttMessageUtils;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static com.itliang.constant.MqttConstants.MQTT_QOS_0;


/**
 * @author : liangzhuoyuan
 */
@Service
@Slf4j
public class SubscribeDataServiceImpl implements SubscribeDataService {

    @Resource
    private EquipmentDataService equipmentDataService;

    @Resource
    private EquipmentService equipmentService;

    @Resource
    private MqttService mqttService;

    @Resource
    private RedisCache redisCache;

    @Override
    public void handlerCollectionData(String message) {

        HardwareData hardwareData = JSON.parseObject(message, HardwareData.class);
        String code = hardwareData.getCode();
        Double data = hardwareData.getData();
        Integer dataType = hardwareData.getDataType();
        equipmentDataService.insertHardData(code, data, dataType, new Date());
    }

    @Override
    public void sendStatusToESP8266(String message) {
        log.error(message);
        HardwareCode hardwareCode = JSON.parseObject(message, HardwareCode.class);
        String thCode = hardwareCode.getThCode();
        String lCode = hardwareCode.getLCode();
        String cCode = hardwareCode.getCCode();
        String led1Code = hardwareCode.getLed1Code();
        String led2Code = hardwareCode.getLed2Code();
        String fengshanCode = hardwareCode.getFengshanCode();
        List<String> stringList = Arrays.asList(thCode, lCode, cCode, led1Code, led2Code, fengshanCode);
        QueryWrapper<Equipment> wrapper = new QueryWrapper<>();
        wrapper.in("code", stringList);
        List<Equipment> list = equipmentService.list(wrapper);
        String json = MqttMessageUtils.hardwareStatus(list);
        try {
            log.info(json);
            mqttService.publish(MqttConstants.SPRINGBOOT_TO_ESP_TOPIC, json, MQTT_QOS_0);
        } catch (MqttException e) {
            // TODO 异常状态
            throw new BusinessException(11111, "MQTT发布错误");
        }
    }

}